<script setup lang="ts">
  import useCheckFlowNodeListService from '@/services/pages/base-info/useCheckFlowNodeListService'
  import { computed, ref, watch } from 'vue'
  import useCheckFlowTemplateWithProcessDetailService from '@/services/pages/base-info/useCheckFlowTemplateWithProcessDetailService'
  import { TableInstance } from 'element-plus'
  import useCheckFlowTemplateWithProcessFormService from '@/services/pages/base-info/useCheckFlowTemplateWithProcessFormService'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import moment from 'moment'

  const {
    checkFlowTemplateWithProcessForm,
    checkFlowTemplateWithProcessFormSaveLoading,
    checkFlowTemplateWithProcessFormSave,
    resetCheckFlowTemplateWithProcessForm,
  } = useCheckFlowTemplateWithProcessFormService()
  const {
    checkFlowTemplateWithProcessDetail,
    getCheckFlowTemplateWithProcessDetailLoading,
    getCheckFlowTemplateWithProcessDetail,
  } = useCheckFlowTemplateWithProcessDetailService()
  const { checkFlowNodeList, getCheckFlowNodeListLoading, getCheckFlowNodeList } =
    useCheckFlowNodeListService()

  defineOptions({
    name: 'EditTemplateProcessModal',
  })

  const props = defineProps({
    templateId: {
      type: String,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'close'): void
    (e: 'update'): void
  }>()

  const visible = defineModel<boolean>('modelValue', { default: false })
  const tableInstance = ref<TableInstance | null>(null)
  const loading = computed(() => {
    return (
      getCheckFlowNodeListLoading.value ||
      getCheckFlowTemplateWithProcessDetailLoading.value ||
      checkFlowTemplateWithProcessFormSaveLoading.value
    )
  })
  const processNodeList = computed(() => {
    const result: Array<string> = []

    checkFlowTemplateWithProcessDetail.value.flowTemplateNodeRelationList.forEach((processNode) => {
      checkFlowNodeList.value.forEach((node) => {
        if (processNode.nodeId === String(node.id)) {
          result.push(node.nodeName)
        }
      })
    })

    return result
  })

  const hideDrawer = () => {
    visible.value = false
    emits('close')
    resetCheckFlowTemplateWithProcessForm()
  }

  const init = async () => {
    await getCheckFlowTemplateWithProcessDetail(props.templateId)
    checkFlowTemplateWithProcessDetail.value.flowTemplateNodeRelationList.forEach((processNode) => {
      checkFlowNodeList.value.forEach((node) => {
        if (processNode.nodeId === String(node.id) && tableInstance.value) {
          tableInstance.value.toggleRowSelection(node, true)
        }
      })
    })
    checkFlowTemplateWithProcessForm.value = checkFlowTemplateWithProcessDetail.value
  }

  const handleTableSelectionChange = (data: Array<BaseInfoAPIResponse.CheckFlowNodeListItem>) => {
    checkFlowTemplateWithProcessForm.value.flowTemplateNodeRelationList = data.map(
      (node, nodeIndex) => {
        let nodeType = 'Tasker'
        if (nodeIndex === 0) {
          nodeType = 'Starter'
        }
        if (nodeIndex === data.length - 1) {
          nodeType = 'Ender'
        }
        return {
          assignType: 'Singal',
          flowTemplateId: '',
          gmtCreate: '',
          gmtUpdate: '',
          id: '',
          nodeId: String(node.id),
          nodeType: nodeType,
          orSignSuccessNumber: '',
          parentNodeId: '',
        }
      },
    )
  }

  const onConfirmClick = async () => {
    if (checkFlowTemplateWithProcessForm.value.flowTemplateNodeRelationList.length <= 0) {
      HMessageBox.error('至少选择一个节点')
      return
    }

    checkFlowTemplateWithProcessForm.value.flowTemplateNodeRelationList =
      checkFlowTemplateWithProcessForm.value.flowTemplateNodeRelationList.map((item) => {
        item.gmtUpdate = moment().format('YYYY-MM-DD HH:mm:ss')
        item.gmtCreate = moment().format('YYYY-MM-DD HH:mm:ss')
        item.flowTemplateId = props.templateId
        return item
      })

    const res = await checkFlowTemplateWithProcessFormSave()
    if (res) {
      if (res.code === 20000) {
        HMessage.success('操作成功')
        hideDrawer()
        emits('update')
        return
      }

      HMessageBox.error(res.message)
      return
    }

    HMessageBox.error('保存失败，请稍后重试')
  }

  watch(visible, async (value) => {
    if (value) {
      await getCheckFlowNodeList()
      await init()
    }
  })
</script>

<template>
  <h-drawer
    v-model="visible"
    title="编辑模板流程"
    :loading="loading"
    unit="px"
    :width="800"
    @close="hideDrawer"
  >
    <div class="edit-template-process-modal">
      <div class="title">模板流程：{{ processNodeList.join('-->') }}</div>
      <el-table
        ref="tableInstance"
        :data="checkFlowNodeList"
        :border="true"
        :stripe="true"
        @selection-change="handleTableSelectionChange"
      >
        <!-- 选择 -->
        <el-table-column type="selection" width="50" fixed="left" :align="'center'" />

        <!-- 序号 -->
        <el-table-column type="index" width="50" :align="'center'" label="序号" />

        <!-- 节点名称 -->
        <el-table-column min-width="150" prop="nodeName" label="节点名称" />

        <!-- 创建时间 -->
        <el-table-column width="150" prop="gmtCreate" label="创建时间" />

        <!-- 更新时间 -->
        <el-table-column width="150" prop="gmtUpdate" label="更新时间" />
      </el-table>
    </div>

    <template #footer>
      <h-button is-modal type="primary" @click="onConfirmClick">确定</h-button>
      <h-button is-modal @click="hideDrawer">取消</h-button>
    </template>
  </h-drawer>
</template>

<style scoped lang="scss">
  .edit-template-process-modal {
    display: flex;
    flex-direction: column;
    row-gap: 4px;

    .title {
      font-size: 14px;
      font-weight: bold;
    }
  }
</style>
